<?php

// +----------------------------------------------------------------------
// | 私信
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\pos;

use app\common\event\Base;
use app\event\pos\Pos as PosEvent;
use app\event\ucenter\MemberInfo;
use app\event\ucenter\User as UserEvent;
use app\model\pos\Store as StoreModel;
use app\model\ucenter\User as UserModel;
use app\model\pos\PosLevel as PosLevelModel;
use app\model\ucenter\MemberInfo as MemberInfoModel;
use app\model\pos\Pos as PosModel;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use think\facade\Db;
use think\Exception;

class PosTrade extends Base
{

    /**
     * pos交易
     */
    public function trade($trade, $pos): array
    {
        try {
            Db::startTrans();
            if ($trade['status'] == 1) {
                $pos['last_use_time'] = time_format();
                $pos['times'] = $pos['times'] + 1;
                if (empty($pos['activate_time'])) {
                    $pos['activate_time'] = time_format();
                }
                $pos->save();
                // 商户统计
                $store = StoreModel::where('store_sn', $trade['merch_no'])->where('status', 1)->find();
                if ($store) {
                    $store['user_id'] = $trade['user_id'];
                    $store['trade'] = $store['trade'] + $trade['amount'];
                    $store['trade_month'] = $store['trade_month'] + $trade['amount'];
                    $store->save();
                }
                // 处理返佣
                $this->_dealFee($pos, $trade);
                // 处理返现
                PosEvent::paybackCheck($pos);
            }
            Db::commit();
            $data['message'] = '获取成功';
            $data['code'] = 0;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 2;
            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }

    protected function _dealFee($pos, $trade)
    {
        //按权益返佣金
        $user = UserModel::where('id', $trade['user_id'])->find();
        if (!$user) {
            throw new Exception('用户不存在');
        }
        $posLevel = PosLevelModel::where('id', $user['pos_level'])->find();
        if (!$posLevel) {
            throw new Exception('等级异常');
        }
        $commission = $this->getPosFee($pos, $trade, $posLevel);

        $log = UserMoneyLogModel::where('user_id', $trade['user_id'])->where('type', 90)
            ->where('order_id', $trade['order_sn'])
            ->where('channel', $trade['channel_id'])->find();
        if ($log) {
            throw new Exception('已经记录');
        }

        $fee = round($trade['amount'] * $commission, 3);//0.6

        if ($fee >= 0.01) {
            //pos交易返佣
            UserEvent::exhibitionIncome($user, $fee, 'POS交易返佣', 90, $user['id'], $trade['order_sn'], 0, $trade['channel_id'], 16);

            if ($user['pid']) {
                $pUser = UserModel::where('id', $user['pid'])->find();
                if ($pUser && $pUser['pos_level']) {
                    // 专属级差
                    $level = MemberInfoModel::where('type', $user['level'])->where('id', '<', 5)->find();
                    if (!$level) {
                        throw new Exception('等级异常');
                    }
                    $user_get = $fee * $level['fee'];

                    $pLevel = MemberInfoModel::where('type', $pUser['level'])->where('id', '<', 5)->find();
                    if (!$level) {
                        throw new Exception('等级异常');
                    }
                    $pposLevel = PosLevelModel::where('id', $pUser['pos_level'])->find();
                    if (!$pposLevel) {
                        throw new Exception('等级异常');
                    }
                    $p_get = $this->getPosFee($pos, $trade, $pposLevel) * $pLevel['fee'];

                    $p_fee = round($trade['amount'] * $p_get, 3);//0.6

                    $has_get = UserMoneyLogModel::where('user_id', $pUser['id'])
                        ->where('type', 'in', '12,13,17')
                        ->where('from_id', $trade['user_id'])
                        ->where('order_id', $trade['order_sn'])
//                        ->where('channel', $trade['channel_id'])
                        ->sum('money');

                    if ($p_fee - $user_get - $has_get >= 0.01) {
                        //专属利差
                        UserEvent::money(round(($p_fee - $user_get - $has_get), 2), $pUser['id'], 'POS专属利差', 95, $user['id'], $trade['order_sn'], 0, $trade['channel_id'], 16);
                    }
                }
            }

            //pos交易返佣 查询用户等级
//            $level = MemberInfoModel::where('type', $user['level'])->where('id', '<', 5)->find();
//            if ($level) {
////                            UserEvent::money(floor($fee*$level['fee'],2), $trade['user_id'], '交易返佣', 90, $trade['id'], $trade['order_sn'],0,$trade['channel_id']);
//                UserEvent::money(floor(100 * $fee * $level['fee']) / 100, $trade['user_id'], '交易返佣', 90, $trade['id'], $trade['order_sn'], 0, $trade['channel_id'],16);
//
//                if ($user['bid']) {
//                    $bUser = UserModel::where('id', $user['bid'])->find();
//                    if ($bUser) {
//                        // 同级奖
//                        $same = MemberInfo::getSame($user, $bUser);
//                        if ($same > 0) {
//                            UserEvent::money(floor(100 * $fee * $same) / 100, $user['bid'], 'POS交易同级奖', 12, $trade['id'], $trade['order_sn'], 0, $trade['channel_id'],16);
//                        }
//                        //级差奖
//                        $same = MemberInfo::getDifferential($user, $bUser);
//                        if ($same > 0) {
//                            UserEvent::money(floor(100 * $fee * $same) / 100, $user['bid'], 'POS交易级差奖', 13, $trade['id'], $trade['order_sn'], 0, $trade['channel_id'],16);
//                        }
//                        //培养
//                        $same = MemberInfo::getBossToBoss($user, $bUser);
//                        if ($same > 0) {
//                            UserEvent::money(floor(100 * $fee * $same) / 100, $user['bid'], 'POS交易培养奖', 17, $trade['id'], $trade['order_sn'], 0, $trade['channel_id'],16);
//                        }
//                        if ($bUser['bid']) {
//                            // 间接推荐
//                            $bbUser = UserModel::where('id', $bUser['bid'])->find();
//                            if ($bbUser) {
//                                //间推奖，必须是老板等级
//                                $same = MemberInfo::getBossIndirectBoss($user, $bUser, $bbUser);
//                                if ($same > 0) {
//                                    UserEvent::money(floor(100 * $fee * $same) / 100, $bUser['bid'], 'POS交易间推奖', 22, $trade['id'], $trade['order_sn'], 0, $trade['channel_id'],16);
//                                }
//
//                                //直接老板,自己不是，给间接培养
//                                $same = MemberInfo::getBossIndirect($user, $bUser, $bbUser);
//                                if ($same > 0) {
//                                    UserEvent::money(floor(100 * $fee * $same) / 100, $bUser['bid'], 'POS交易间接培养奖', 17, $trade['id'], $trade['order_sn'], 0, $trade['channel_id'],16);
//                                }
//
//                            }
//
//                        }
//                    }
//                }
//            }
        }
    }

    /**
     * 获取当前交易可以获得佣金
     * @param $pos
     * @param $trade
     * @param $posLevel
     * @return float|int
     */
    protected function getPosFee($pos, $trade, $posLevel)
    {
        if ($pos['is_level'] == 1) {

            /**
             * 等级产品    V1:数量/分润    V2:数量/分润    V3:数量/分润
             * 拉卡拉电签    1台/刷7扫6    5台/刷8扫7    50台/刷9扫8
             * 嘉联微电签    1台/刷7扫6    5台/刷7.5扫7    50台/刷8扫8
             * 盛付通电签    1台/刷7扫6    5台/刷8扫7    50台/刷8.5扫8
             *
             */
            if ($trade['trade_type'] == 2 || ($trade['channel_id'] == 1 && $trade['card_type'] == 1)) {
                // 扫码
                if ($posLevel['id'] == 1) {
                    $commission = 0.0006;
                } elseif ($posLevel['id'] == 2) {
                    $commission = 0.0007;
                } else {
                    $commission = 0.0008;
                }
                if ($trade['channel_id'] == 1 && $trade['card_type'] == 1 && $trade['amount'] >= 4000) {
                    $commission = 0;
                }
            } else {
                // 刷卡
                if ($trade['channel_id'] == 0) {
                    // 嘉联刷卡
                    if ($posLevel['id'] == 1) {
                        $commission = 0.0007;
                    } elseif ($posLevel['id'] == 2) {
                        $commission = 0.00075;
                    } else {
                        $commission = 0.0008;
                    }
                } elseif ($trade['channel_id'] == 2) {
                    // 盛付通
                    if ($posLevel['id'] == 1) {
                        $commission = 0.0007;
                    } elseif ($posLevel['id'] == 2) {
                        $commission = 0.0008;
                    } else {
                        $commission = 0.00085;
                    }
                } else {
                    $commission = $posLevel['commission'];
                }
            }
        } else {
            // 全局固定金额
            $commission = 0.0007;
        }
        return $commission;
    }

    /**
     * 划转预览
     * @param array $param
     * @param UserModel $user
     */
    public function priview(UserModel $user, array $param): array
    {
        try {
            if (!$user) {
                throw new Exception('游客信息异常');
            }
            if ($param['type'] == 'check') {
                // 逐个调拨
                $pos = PosModel::where('sn', $param['sn'])->where('user_id', $user['id'])->whereNun('activate_time')->select();
            } else {
                $pos = PosModel::where('sn', '>=', $param['sn'])->limit($param['num'])->order('sn ASC')->where('user_id', $user['id'])->whereNun('activate_time')->select();
            }
//            Db::startTrans();
            $data['data']['lists'] = $pos;
            $data['data']['num'] = count($pos);
            $data['code'] = 0;
//            Db::commit();
            $data['message'] = '获取成功';
        } catch (\Exception $e) {
            // 回滚事务
//            Db::rollback();
            $data['code'] = 2;
            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }


}
